package service

import (
	"errors"
	"github.com/gin-gonic/gin"
	"mime/multipart"
	"strings"
)

type UploadService struct {
	Path        string   //需要上传的文件地址
	NewFileName string   //新的文件名
	Suffix      []string //后缀过滤
	MaxFile     int64    //文件最大的大小限制
	Resource    *multipart.FileHeader
	Context     *gin.Context
}

func (u *UploadService) Upload() (filePath string, err error) {
	err = suffixValidation(u.Resource.Filename, u.Suffix)
	if err != nil {
		return "", err
	}
	//开始文件上传copy
	filePath = u.Path + u.NewFileName
	if u.NewFileName == "" {
		filePath = u.Path + u.Resource.Filename
	}
	err = u.Context.SaveUploadedFile(u.Resource, filePath)
	if err != nil {
		return "", err
	}
	return filePath, nil
}

func suffixValidation(fileName string, suffix []string) error {
	if suffix != nil {
		res := false
		for _, v := range suffix {
			res = strings.HasSuffix(fileName, v)
			if res == true {
				break
			}
		}
		if res == false {
			return errors.New("不支持该格式文件上传")
		}
	}
	return nil
}
